<?php

namespace app\common\library;


class CryptDes
{

    const KEY = 'tongjieck1408';


    //des加密（cbc模式）
    public function encrypt($str, $key = '')
    {
        $key = $key ? $key : self::KEY;
        $str = $this->pkcsPadding($str, 8);
        $v = pack('H*', "1234567890abcdef");
        $key = str_pad($key, 8, '0'); //3DES加密将8改为24
        $sign = openssl_encrypt($str, 'DES-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$v);
        $sign = base64_encode($sign);
        return $sign;
    }


    //des解密（cbc模式）
    public function decrypt($encrypted, $key = '')
    {
        $key = $key ? $key : self::KEY;
        $encrypted = base64_decode($encrypted);
        $v = pack('H*', "1234567890abcdef");
        $key = str_pad($key, 8, '0'); //3DES加密将8改为24
        $sign = @openssl_decrypt($encrypted, 'DES-CBC', $key,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$v);
        $sign = $this->unPkcsPadding($sign);
        $sign = rtrim($sign);
        return $sign;
    }

    /**
     * 填充
     *
     * @param $str
     * @param $blocksize
     * @return string
     */
    private function pkcsPadding($str, $blocksize)
    {
        $pad = $blocksize - (strlen($str) % $blocksize);
        return $str . str_repeat(chr($pad), $pad);
    }

     /**
     * 去填充
     * 
     * @param $str
     * @return string
     */
    private function unPkcsPadding($str)
    {
        $pad = ord($str{strlen($str) - 1});
        if ($pad > strlen($str)) {
            return false;
        }
        return substr($str, 0, -1 * $pad);
    }
}